package com.lishe.lishe.lishe.module.excitation.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnMessageChangeListener;
import com.lishe.lishe.lishe.module.excitation.presenter.MinePresenter;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.lishe.lishe.retrofit.DataResponseListener;

/**
 * Created by DELL on 2017/10/30.
 */

public class ShowSendCommentDialog extends Dialog {


    public ShowSendCommentDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
    }

    public static class Builder {
        private Activity context;
        private ShowSendCommentDialog dialog;
        private String eventId;//事件id
        private OnMessageChangeListener listener;
        private String strComment;
        private boolean isLoading = false;
        private InputMethodManager inputManager;


        public Builder(Activity context) {
            this.context = context;
            inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        }

        private void showSoftInput() {
            inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);
        }

        /**
         * 设置事件id
         *
         * @param eventId
         * @return
         */
        public Builder setEventId(String eventId) {
            this.eventId = eventId;
            return this;
        }

        /**
         * 设置回调提醒
         *
         * @param listener
         * @return
         */
        public Builder setOnMessageChangeListener(OnMessageChangeListener listener) {
            this.listener = listener;
            return this;
        }

        public Builder setCommnet(String commnet) {
            this.strComment = commnet;
            return this;
        }

        public ShowSendCommentDialog create() throws NullPointerException {

            if (listener == null) {
                throw new NullPointerException("OnMessageChangeListener is null,do you have setOnMessageChangeListener?");
            }

            if (dialog == null) {
                dialog = new ShowSendCommentDialog(context, R.style.MyDialog);
                View contentView = context.getLayoutInflater().inflate(R.layout.dialog_send_comment, null);

                final EditText comment = contentView.findViewById(R.id.comment);
                final TextView commit = contentView.findViewById(R.id.commit);
                final TextView textNum = contentView.findViewById(R.id.textNum);
                final TextView num = contentView.findViewById(R.id.num);
                final LinearLayout linearNum = contentView.findViewById(R.id.ll_num);
                final LinearLayout linear = contentView.findViewById(R.id.ll1);

                showSoftInput();
                linear.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        inputManager.hideSoftInputFromWindow(comment.getWindowToken(), 0);
                        dissmiss();
                    }
                });

                comment.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int textLength = s.toString().trim().length();

                        if (textLength > 0) {
                            commit.setTextColor(context.getResources().getColor(R.color.color4138));
                        } else {
                            commit.setTextColor(context.getResources().getColor(R.color.color_cccccc));
                        }

                        if (textLength > 10) {
                            textNum.setVisibility(View.GONE);
                            linearNum.setVisibility(View.VISIBLE);
                        } else {
                            textNum.setVisibility(View.VISIBLE);
                            linearNum.setVisibility(View.GONE);
                            textNum.setText(String.valueOf(textLength) + "/140");
                        }

                        if (textLength > 140) {
                            SpannableString ss = new SpannableString(s.toString());
                            ss.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.color_cccccc)), 140, textLength, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
                            comment.removeTextChangedListener(this);
                            comment.setText(ss);
                            comment.setSelection(ss.length());
                            comment.addTextChangedListener(this);
                            commit.setTextColor(context.getResources().getColor(R.color.color_cccccc));


                            num.setTextColor(context.getResources().getColor(R.color.color4138));
                            num.setText(String.valueOf(textLength));
                        } else {
                            if (linearNum.getVisibility() == View.VISIBLE) {
                                num.setTextColor(context.getResources().getColor(R.color.color_999999));
                                num.setText(String.valueOf(textLength));
                            }

                            commit.setTextColor(context.getResources().getColor(R.color.color4138));
                        }

                    }
                });


                commit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        strComment = comment.getText().toString().trim();
                        if (TextUtils.isEmpty(strComment)) {
                            return;
                        }
                        if (strComment.length() > 140) {
                            toast("字数不符合");
                        } else {
                            if (!isLoading) {
                                addComment();
                                inputManager.hideSoftInputFromWindow(comment.getWindowToken(), 0);
                            }
                        }
                    }
                });


                dialog.setContentView(contentView);
                dialog.getWindow().setGravity(Gravity.BOTTOM);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(true);
                WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(lp);
            }
            return dialog;
        }

        public void show() {
            try {
                create();
                if(dialog!=null&&!dialog.isShowing()){
                    dialog.show();
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

        public void dissmiss() {
            if (dialog != null) {
                dialog.dismiss();
                dialog.cancel();
            }
            if (listener != null) {
                listener = null;
            }
        }

        private void addComment() {
            try {
                MinePresenter.getInstance().addEventComment(Globals.getToken(), StringUtils.stringToUtf8(strComment), eventId, new DataResponseListener() {
                    @Override
                    public void onPrepare() {
                        super.onPrepare();
                        isLoading = true;
                        LoadingUtils.createLoadingDialog(context, "请稍候...", false);
                    }

                    @Override
                    public void onSuccess(Object dataResponse) {
                        isLoading = false;
                        LoadingUtils.closeDialog();
                        toast("评论成功");
                        listener.messageChange(OnMessageChangeListener.COMMENT_CHANGE_SUCCESS, 1);
                        dissmiss();
                    }

                    @Override
                    public void onFail(String failMessage) {
                        toast(failMessage);
                        LoadingUtils.closeDialog();
                        isLoading = false;
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        toast(context.getString(R.string.network_or_server_exception));
                        LoadingUtils.closeDialog();
                        isLoading = false;
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                toast(context.getString(R.string.data_parse_fail));
                LoadingUtils.closeDialog();
                isLoading = false;
            }
        }

        private void toast(String message) {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }

    }

}
